package com.fdb.efp.esb.service.client;

import static java.util.stream.Collectors.toList;

import java.nio.charset.Charset;
import java.util.List;
import java.util.Objects;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

/**
 * @description:HTTP客户端
 * 				内部使用JDK的HttpURLConnection
 * @see org.springframework.http.client.SimpleClientHttpRequestFactory.SimpleClientHttpRequestFactory()
 * @date:2018年12月18日 上午9:26:17
 * @author:hengyh
 */
public class SimpleHttpClientFactory implements HttpClientFactory {
	
	private static final Logger log = LoggerFactory.getLogger(SimpleHttpClientFactory.class);
	private RestTemplate restTemplate;
	
	public static SimpleHttpClientFactory newInstance(int timeout) {
		SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
		requestFactory.setReadTimeout(timeout);
		requestFactory.setConnectTimeout(timeout);
		
		RestTemplate temp = new RestTemplate();
		List<HttpMessageConverter<?>> messageConverters = temp.getMessageConverters();
		messageConverters = messageConverters.stream()
						 .filter(i -> !StringHttpMessageConverter.class.isInstance(i))
						 .collect(toList());
		messageConverters.add(new StringHttpMessageConverter(Charset.forName("utf-8")));
		temp.setRequestFactory(requestFactory);
		temp.setErrorHandler(new DefaultResponseErrorHandler());
		SimpleHttpClientFactory factory = new SimpleHttpClientFactory();
		factory.setClient(temp);
		log.info("SimpleHttpClient初始化完成");
		return factory;
	}
	
	public RestTemplate getClient() {
		return Objects.requireNonNull(restTemplate); // must be inited
	}

	public void setClient(RestTemplate restTemplate) {
		this.restTemplate = restTemplate;
	}
	
	private SimpleHttpClientFactory() { }
}
